# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
# p=TreeNode(1)
# p.left=TreeNode(2)
# p.right=TreeNode(3)
# q=TreeNode(1)
# q.left=TreeNode(2)
# q.right=TreeNode(3)
p=TreeNode(1)
p.right=TreeNode(1)
q=TreeNode(1)
q.right=TreeNode(1)
def dfs(p,q):
    if p.val==q.val:
        if (p.left==None and p.right==None) and (q.right==None and q.left==None):
            return True
        if (p.left==None and q.left!=None) or (p.left!=None and q.left==None):
            return False
        if (p.right==None and q.right!=None) or (p.right!=None and q.right==None):
            return False
        leftFlag=None
        rightFlag=None
        if p.left!=None and q.left!=None:
            leftFlag=dfs(p.left,q.left)
        if p.right!=None and q.right!=None:
            rightFlag=dfs(p.right,q.right)
        if (leftFlag==None or leftFlag==True)  and (rightFlag==None or rightFlag==True):
            return True
        else:
            return False
    else:
        return False

def isSameTree(p,q):
    return dfs(p,q)

print(isSameTree(p,q))